package com.youi.web;


import com.youi.common.Common;
import com.youi.common.SessionKey;
import com.youi.entity.Goods;
import com.youi.entity.MarketTheme;
import com.youi.entity.MarketThemeGoods;
import com.youi.entity.Sysuser;
import com.youi.exception.BusinessException;
import com.youi.manage.HttpRequestManage;
import com.youi.manage.HttpSessionManage;
import com.youi.service.GoodsService;
import com.youi.service.MarketThemeGoodsService;
import com.youi.service.MarketThemeService;
import com.youi.service.OperationlogService;
import com.youi.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.*;

/**
 * 营销专题控制层
 *
 * @author jenran
 */
@RestController
@RequestMapping("/sysUserGetInfo")  //sysUserGetInfo
public class MarketThemeController extends HttpRequestManage {
    @Autowired
    private MarketThemeService marketThemeService;
    @Autowired
    private MarketThemeGoodsService marketThemeGoodsService;
    @Autowired
    private OperationlogService operationlogService;
    @Autowired
    private GoodsService goodsService;

    /**
     * I-
     * 根据id查询专题（包含marketThemeGoods信息）
     */
    @RequestMapping("getMarketThemeById")
    public String getMarketThemeById(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException {
        Long id = getLong("id", request);
        MarketTheme marketTheme = marketThemeService.get(id);
        if (marketTheme == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "不存在此专题");
        }
        Map<String, Object> params = new HashMap();
        params.put(Common.DELSTATUS, 0);
        params.put("themeId", marketTheme.getId());
        List<MarketThemeGoods> marketThemeGoodsList = marketThemeGoodsService.getByParams(params);
        List<MarketThemeGoods> headers = new ArrayList();
        List<MarketThemeGoods> goods = new ArrayList();
        List<MarketThemeGoods> advertisements = new ArrayList();
        for (MarketThemeGoods marketThemeGoods : marketThemeGoodsList) {
            Goods goodsDetails = goodsService.get(marketThemeGoods.getGoodsId());
            goodsService.getGoodsMsg(goodsDetails);
            marketThemeGoods.setGoods(goodsDetails);
            if (marketThemeGoods.getGoodsPosition() == 1) {
                headers.add(marketThemeGoods);
            } else if (marketThemeGoods.getGoodsPosition() == 2) {
                goods.add(marketThemeGoods);
            } else if (marketThemeGoods.getGoodsPosition() == 3) {
                advertisements.add(marketThemeGoods);
            }
        }
        marketTheme.setHeaders(headers);
        marketTheme.setGoods(goods);
        marketTheme.setAdvertisements(advertisements);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", marketTheme);//jsonObject	json对象
    }

    /**
     * I-
     * 查询专题列表(条件搜索)
     */
    @RequestMapping("getMarketThemeList")
    public String getMarketThemeList(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException {
        //查询已结束但状态未变更的专题变更为结束状态
        marketThemeService.updateThemeEndedStatus();

        Integer pageIndex = optInteger("pageIndex", request, 1);
        Integer pageNum = optInteger("pageNum", request, 10);
        Map<String, Object> sortPram = new HashMap<String, Object>();
        sortPram.put(Common.ID, Common.DESC);
        Map<String, Object> params = new HashMap();
        params.put(Common.DELSTATUS, 0);
        String themeName = optString("themeName", request);
        if (themeName == null) {
            themeName = "";
        }
        if (!themeName.equals("")) {
            params.put("name", themeName);
        }
        String code = optString("code", request);
        if (code == null) {
            code = "";
        }
        if (!code.equals("")) {
            params.put("code", code);
        }
        Integer status = optInteger(Common.STATUS, request);
        if (status != null) {
            params.put("status", status);
        }
        //配置位置
        Integer position = optInteger("position", request);
        if (position != null) {
            params.put("position", position);
        }
        //是否配置 0：全部 1：是 2：否
        Integer isSetting = optInteger("isSetting",request);
        if(isSetting != null){
            if(isSetting==1){
                params.put("position", Arrays.asList(1,2,3,4,5,6,7,8,9,10,11,12));
            }
            if(isSetting==2){
                params.put("position", 0);
            }
        }

        Date gmtEnabledStart = optDate("gmtEnabledStart", request, "yyyy-MM-dd HH:mm:ss");
        Date gmtEnabledEnd = optDate("gmtEnabledEnd", request, "yyyy-MM-dd HH:mm:ss");
        Date gmtBeginStart = optDate("gmtBeginStart", request, "yyyy-MM-dd HH:mm:ss");
        Date gmtBeginEnd = optDate("gmtBeginEnd", request, "yyyy-MM-dd HH:mm:ss");
        Map<String, Object> gtParams = null;
        Map<String, Object> ltParams = null;
        if (gmtEnabledStart != null) {
            if (gtParams == null) {
                gtParams = new HashMap();
            }
            gtParams.put("gmtEnabled", gmtEnabledStart);
        }
        if (gmtBeginStart != null) {
            if (gtParams == null) {
                gtParams = new HashMap();
            }
            gtParams.put("gmtBegin", gmtBeginStart);
        }
        if (gmtBeginEnd != null) {
            if (ltParams == null) {
                ltParams = new HashMap();
            }
            ltParams.put("gmtBegin", gmtBeginEnd);
        }
        if (gmtEnabledEnd != null) {
            if (ltParams == null) {
                ltParams = new HashMap();
            }
            ltParams.put("gmtEnabled", gmtEnabledEnd);
        }
        List<MarketTheme> marketThemeList = marketThemeService.getByParamsList(params, null, sortPram, (pageIndex - 1) * pageNum, pageNum, gtParams, ltParams);
        Integer pageCount = marketThemeService.getCountByParamss(params, null, gtParams, ltParams);
        modelMap.put(CommonInfoUtil.PAGECOUNT, Page.getCount(pageCount, pageNum));//pageCount  总页数
        modelMap.put(CommonInfoUtil.PAGEINDEX, pageIndex);            //pageIndex     查询页数
        modelMap.put(CommonInfoUtil.ALLCOUINT, pageCount);
        modelMap.put(CommonInfoUtil.DATA, marketThemeList);        //jsonObjectList json对象集合
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", modelMap);
    }


    /**
     * I-
     * 根据id删除专题
     */
    @RequestMapping("deleteMarketThemeByIds")
    public String deleteMarketThemeByIds(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException {
        String ids = getString("ids", request);
        Map<String, Object> params = new HashMap();
        if (ids != null && ids.trim().length() > 0) {
            List<Long> idsList = ObjectUtil.getIdListByIds(ids);
            if (idsList == null || idsList.size() == 0) {
                return JsonUtil.toJson(CommonInfoUtil.PARAMERROR, "ids参数错误");
            }
            params.put(Common.ID, idsList);
        } else {
            params.put(Common.ID, -1);
        }
        params.put(Common.DELSTATUS, 0);
        List<MarketTheme> marketThemeList = marketThemeService.getByParams(params);
        if (marketThemeList.size() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "不存在此专题");
        }
        for (MarketTheme marketTheme : marketThemeList) {
            marketTheme.setDelStatus(1);
            marketThemeGoodsService.updateDelStatusByThemeId(1, marketTheme.getId());
        }
        marketThemeService.saveOrUpdateAll(marketThemeList);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");
    }

    /**
     * I-
     * 根据id变更专题状态
     */
    @RequestMapping("updateMarketThemeStatusByIds")
    public String updateMarketThemeStatusByIds(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException {
        String ids = getString("ids", request);
        System.out.println(ids);
        Map<String, Object> params = new HashMap();
        if (ids != null && ids.trim().length() > 0) {
            List<Long> idsList = ObjectUtil.getIdListByIds(ids);
            if (idsList == null || idsList.size() == 0) {
                return JsonUtil.toJson(CommonInfoUtil.PARAMERROR, "ids参数错误");
            }
            params.put(Common.ID, idsList);
        } else {
            params.put(Common.ID, -1);
        }
        params.put(Common.DELSTATUS, 0);
        Integer status = getInteger(Common.STATUS, request);
        List<MarketTheme> marketThemeList = marketThemeService.getByParams(params);
        if (marketThemeList.size() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "不存在此专题");
        }
        if (!(status == 1 || status == 2)) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "禁止此状态的修改");
        }
        for (MarketTheme marketTheme : marketThemeList) {
            if (status == 1) {
                if (marketTheme.getPosition() == 0) {
                    return JsonUtil.toJson(CommonInfoUtil.ERROR, "专题存在未配置状态，禁止启用");
                }
                marketTheme.setGmtEnabled(new Date());
            }
            if (status == 2) {
                marketTheme.setGmtDisabled(new Date());
            }
            marketTheme.setStatus(status);
        }
        marketThemeService.saveOrUpdateAll(marketThemeList);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");
    }


    /**
     * I-
     * 添加或编辑专题信息
     *
     * @param modelMap
     * @param request
     * @return
     * @throws BusinessException
     * @throws ParseException
     */
    @ResponseBody
    @RequestMapping("addOrEditMarketTheme")
    public String addOrEditMarketTheme(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException {
        synchronized ("edit") {
            Sysuser sysuser = (Sysuser) HttpSessionManage.getAttribute(request, SessionKey.SYSUSER);
//            Sysuser sysuser= new Sysuser();
//            sysuser.setId(Long.valueOf("1"));
//            sysuser.setType(0);  //测试用
            Long id = optLong("id", request);
            MarketTheme marketTheme = marketThemeService.get(id);
            if (marketTheme == null) {
                id = null;
            }
            if (sysuser.getType() == 1) {
                return JsonUtil.toJson(CommonInfoUtil.OBJECTEXIST, "商家无权限编辑");
            }

            String themeName = getString("name", request);
            if (themeName == null) {
                themeName = "";
            }
            if (themeName.equals("")) {
                return JsonUtil.toJson(CommonInfoUtil.NEEDPERMISSIONS, "专题名称不能为空");
            }
            Date gmtBegin = optDate("gmtBegin", request, "yyyy-MM-dd HH:mm:ss");
            if (gmtBegin == null) {
                return JsonUtil.toJson(CommonInfoUtil.NEEDPERMISSIONS, "开始时间不能为空");
            }
            Date gmtEnd = optDate("gmtEnd", request, "yyyy-MM-dd HH:mm:ss");
            if (gmtEnd == null) {
                return JsonUtil.toJson(CommonInfoUtil.NEEDPERMISSIONS, "结束时间不能为空");
            }
            String headers = getString("headers", request);
            String goods = getString("goods", request);
            String advertisements = getString("advertisements", request);
            String ip = IpUtil.getIpAddr(request);
            Map<String, String> result = marketThemeService.saveOrEditMarketTheme(id, marketTheme, ip, sysuser, themeName, gmtBegin, gmtEnd, headers, goods, advertisements);
            System.out.println(result);
            if (result.get("code").equals("-1")) {
                return JsonUtil.toJson(CommonInfoUtil.NEEDPERMISSIONS, result.get("msg"));
            }
            return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");
        }
    }

    /**
     * I-
     * 根据id变更专题状态
     */
    @RequestMapping("settingMarketThemeById")
    public String settingMarketThemeById(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException {
        Long id = getLong("id", request);
        String imgUrl = getString("imgUrl", request);
        Integer position = getInteger("position", request);
        if (imgUrl.equals("")) {
            return JsonUtil.toJson(CommonInfoUtil.NOPERMISSIONS, "图片不能为空");
        }

        MarketTheme marketTheme = marketThemeService.get(id);
        if (marketTheme == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "不存在此专题");
        }


        if (position != 0) {
            Map<String, Object> params = new HashMap();
            params.put("position", position);
            params.put(Common.DELSTATUS, 0);
            List<MarketTheme> marketThemeList = marketThemeService.getByParams(params);
            if (marketThemeList.size() > 0) {
                for (MarketTheme marketThemeOld : marketThemeList) {
                    marketThemeOld.setPosition(0);
                }
                //覆盖现有的位置，恢复未配置状态
                marketThemeService.saveOrUpdateAll(marketThemeList);
            }
        }

        marketTheme.setImgUrl(imgUrl);
        marketTheme.setPosition(position);
        marketThemeService.saveOrUpdate(marketTheme);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");
    }

}
